package com.sanji.sjmallmodule.order;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sanji.sjmallapp.MallApplication;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallmodule.goods.GoodsDetailsActivity;
import com.sanji.sjmallutils.ImageUtil;
import com.sanji.sjmallutils.SharePreferenceUtil;
import com.sanji.sjmallwidget.NumControlView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by zsf on 17-1-3.
 */

public class ShopcarAdapter extends BaseExpandableListAdapter implements NumControlView.OnNumChangeListener{

    private Context mCtx;
    private List<ShopcarGroupBean> mShopcarList = new ArrayList<>();

    private int imgWidth;

    private MoneyChangeListener mMoneyChangeListener;

    private boolean isChildSelect = false;

    private SharePreferenceUtil myShare;

    public ShopcarAdapter(Context context, List<ShopcarGroupBean> list) {
        this.mCtx = context;
        this.mShopcarList = list;
        myShare = MallApplication.myShare;

        imgWidth = ImageUtil.setImageWidth(context, 4);
    }

    public void notifyAdapter(List<ShopcarGroupBean> list) {
        this.mShopcarList = list;
        this.notifyDataSetChanged();
    }

    @Override
    public int getGroupCount() {
        int size = mShopcarList.size();
        return size;
    }

    @Override
    public int getChildrenCount(int i) {
        int size = mShopcarList.get(i).getDestList().size();
        return size;
    }

    @Override
    public ShopcarGroupBean getGroup(int i) {
        return mShopcarList.get(i);
    }

    @Override
    public ShopcarChildBean getChild(int i, int i1) {
        return mShopcarList.get(i).getDestList().get(i1);
    }

    @Override
    public long getGroupId(int i) {
        return i;
    }

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
        ViewGroupHolder groupHolder;
        if (view == null) {
            view = LayoutInflater.from(mCtx).inflate(R.layout.item_shopcar_type, null);
            groupHolder = new ViewGroupHolder(view);
            view.setTag(groupHolder);
        } else {
            groupHolder = (ViewGroupHolder) view.getTag();
        }

        ShopcarGroupBean groupBean = getGroup(i);
//        String title = "手机";
//        if("Accessory".equals(groupBean.getGoodsSpec())){
//            title = "配件";
//        }
        groupHolder.mShopcarTypeItemCb.setText(groupBean.getGoodsSpec());
        groupHolder.mShopcarTypeItemCb.setChecked(groupBean.isAllSelected());
        groupHolder.mShopcarTypeItemCb.setOnClickListener(new GroupCheckBoxClick(i));

        return view;
    }

    @Override
    public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
        ViewChildHolder childHolder;
        if (view == null) {
            view = LayoutInflater.from(mCtx).inflate(R.layout.item_shopcar_dest, null);
            childHolder = new ViewChildHolder(view);
            view.setTag(childHolder);
        } else {
            childHolder = (ViewChildHolder) view.getTag();
        }

        childHolder.mShopcarItemDestImg.setLayoutParams(new RelativeLayout.LayoutParams(imgWidth, imgWidth));

        ShopcarChildBean childBean = getChild(i, i1);

        childHolder.mShopcarItemDestTitle.setText(childBean.getGoodsName());
        if ("手机".equals(childBean.getGroupTitle())){
            childHolder.mShopcarItemDestSpec.setText(mCtx.getResources().getString(R.string.spec) + childBean.getGoodsSpec());
        }else{
            childHolder.mShopcarItemDestSpec.setText(mCtx.getResources().getString(R.string.color) + childBean.getColor());
        }
        if (childBean.getGoodsCount() > childBean.getInventoryCount()){
            childHolder.mShopcarItemStock.setTextColor(mCtx.getResources().getColor(R.color.colorRed));
        }else{
            childHolder.mShopcarItemStock.setTextColor(mCtx.getResources().getColor(R.color.color_9e9e9e));
        }
        childHolder.mShopcarItemStock.setText(mCtx.getResources().getString(R.string.stock)+childBean.getInventoryCount());
        Glide.with(mCtx).load(childBean.getImgUrl()).centerCrop().placeholder(R.mipmap.default_3j_img)
                //当加载图片失败时，通过error(Drawable drawable)方法设置加载失败后的图片显示
                .error(R.mipmap.default_3j_img)
                .crossFade().into(childHolder.mShopcarItemDestImg);
        childHolder.mShopcarItemDestPrice.setText(mCtx.getResources().getString(R.string.price_title) + childBean.getGoodsPrice());
        childHolder.mShopcarItemDestNum.setOnNumChangeListener(this);
        childHolder.mShopcarItemDestNum.setTag(i + "," + i1);
        childHolder.mShopcarItemDestNum.setGoodsParameter(childBean.getInventoryCount(), childBean.getLimitCount(), childBean.getGoodsCount(),childBean.isSelected());
        childHolder.mShopcarItemDestCb.setChecked(childBean.isSelected());
        childHolder.mShopcarItemDestCb.setOnClickListener(new ChildCheckBoxClick(i, i1));

        List<String> giftList = childBean.getGiftList();
        childHolder.mShopcarItemDestGiftLayout.removeAllViews();
        if (giftList != null && giftList.size() > 0) {
            for (String str : giftList) {
                View giftView = LayoutInflater.from(mCtx).inflate(R.layout.item_gift, null);
                TextView gift = (TextView) giftView.findViewById(R.id.gift_item_tv);
                gift.setText(str);
                childHolder.mShopcarItemDestGiftLayout.addView(giftView);
            }
        }

        if (getGroup(i).isAllDelete() || childBean.isDelete()){
            childHolder.deleLayout.setVisibility(View.VISIBLE);
        }else{
            childHolder.deleLayout.setVisibility(View.GONE);
        }

        childHolder.deleLayout.setOnClickListener(new DeleLayoutClick(i,i1));

        childHolder.mShopcarItemDestLayout.setTag(i + "," + i1);
        childHolder.mShopcarItemDestLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String tag = (String) view.getTag();
                String[] pos = tag.split(",");
                int group = Integer.parseInt(pos[0]);
                int child = Integer.parseInt(pos[1]);
                ShopcarChildBean childBean = getChild(group, child);
                String goodsType;
                if (mCtx.getResources().getString(R.string.phone).equals(childBean.getGroupTitle())){
                    goodsType = "sj";
                }else{
                    goodsType = "accessory";
                }
                Intent intent = new Intent(mCtx,GoodsDetailsActivity.class);
                intent.putExtra("goodsCode", childBean.getGoodsNum());
                intent.putExtra("goodsType", goodsType);
                mCtx.startActivity(intent);

            }
        });
        return view;
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }

    @Override
    public void onNumChange(final View view, final int num) {
        String tag = (String) view.getTag();
        String[] tags = tag.split(",");
        int group = Integer.parseInt(tags[0]);
        int child = Integer.parseInt(tags[01]);

        if (mMoneyChangeListener != null) {
            mMoneyChangeListener.onNumChange(view,group,child,num);
        }

    }

    static class ViewGroupHolder {
        @BindView(R.id.shopcar_type_item_cb)
        CheckBox mShopcarTypeItemCb;

        ViewGroupHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    static class ViewChildHolder {
        @BindView(R.id.shopcar_item_dest_layout)
        FrameLayout mShopcarItemDestLayout;
        @BindView(R.id.shopcar_item_dest_cb)
        CheckBox mShopcarItemDestCb;
        @BindView(R.id.shopcar_item_dest_img)
        ImageView mShopcarItemDestImg;
        @BindView(R.id.shopcar_item_dest_title)
        TextView mShopcarItemDestTitle;
        @BindView(R.id.shopcar_item_dest_spec)
        TextView mShopcarItemDestSpec;
        @BindView(R.id.shopcar_item_stock)
        TextView mShopcarItemStock;
        @BindView(R.id.shopcar_item_dest_price)
        TextView mShopcarItemDestPrice;
        @BindView(R.id.shopcar_item_dest_num)
        NumControlView mShopcarItemDestNum;
        @BindView(R.id.shopcar_item_dest_gift_layout)
        LinearLayout mShopcarItemDestGiftLayout;
        @BindView(R.id.shopcar_dest_item_dele_layout)
        TextView deleLayout;

        ViewChildHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }



    public void setOnMoneyChangeListener(MoneyChangeListener listener) {
        this.mMoneyChangeListener = listener;
    }

    public interface MoneyChangeListener {
        void onMoneyChange();
        void onNumChange(View view,int group,int child,int num);
    }


    /**
     * group
     */
    class GroupCheckBoxClick implements View.OnClickListener {
        private int groupPos;

        GroupCheckBoxClick(int pos) {
            this.groupPos = pos;
        }

        @Override
        public void onClick(View view) {
            getGroup(groupPos).toggle();

            int childCount = getGroup(groupPos).getDestList().size();
            boolean groupIsChecked = getGroup(groupPos).isAllSelected();
            for (int i = 0; i < childCount; i++) {
                getGroup(groupPos).getDestList().get(i).setSelected(groupIsChecked);
            }

            notifyDataSetChanged();

            if (mMoneyChangeListener != null) {
                mMoneyChangeListener.onMoneyChange();
            }
        }
    }

    /**
     * child
     */
    class ChildCheckBoxClick implements View.OnClickListener {

        private int groupPos;
        private int childPos;

        ChildCheckBoxClick(int group, int child) {
            this.groupPos = group;
            this.childPos = child;
        }

        @Override
        public void onClick(View view) {
            handleClick(childPos, groupPos);
        }
    }

    public void handleClick(int child, int group) {
        getGroup(group).getDestList().get(child).toggle();

        //检查child cb 是否有全部勾选，以控制 group cb
        int childCount = getGroup(group).getDestList().size();
        boolean childAllIsChecked = true;
        for (int i = 0; i < childCount; i++) {
            if (!getGroup(group).getDestList().get(i).isSelected()) {
                childAllIsChecked = false;
            }
        }
        getGroup(group).setAllSelected(childAllIsChecked);

        notifyDataSetChanged();

        if (mMoneyChangeListener != null) {
            mMoneyChangeListener.onMoneyChange();
        }
    }


//    @Override
//    public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
//        handleClick(i1, i);
//        return true;
//    }

    /**
     * 删除项取消
     */
    class DeleLayoutClick implements View.OnClickListener{

        private int groupPos;
        private int childPos;

        DeleLayoutClick(int group,int child){
            this.groupPos = group;
            this.childPos = child;
        }

        @Override
        public void onClick(View view) {
            ShopcarChildBean childBean = getChild(groupPos,childPos);
            childBean.setDelete(false);
            childBean.setSelected(false);
            getGroup(groupPos).setAllDelete(false);
            getGroup(groupPos).setAllSelected(false);

            notifyDataSetChanged();
        }
    }



}
